package com.quectel.taskserver.mock.job;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.RandomUtil;
import com.quectel.constant.core.device.DeviceCategoryCodeConstants;
import com.quectel.core.module.car.dto.CarDto;
import com.quectel.core.module.car.dto.mongo.MongoCarAccessRecordDto;
import com.quectel.core.module.car.service.CarService;
import com.quectel.core.module.car.service.mongo.MongoCarAccessRecordService;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.prewarning.service.PreWarningRecordService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.taskserver.mock.MockLimit;
import com.quectel.taskserver.mock.vo.GenerateCarRecordVo;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.kit.StorageKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.security.SecureRandom;
import java.util.*;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2022/4/12 下午2:56
 * 模拟生成小区内的车辆进出记录以及频繁进出预警记录
 */
@Component
@Slf4j
public class YsxqCarRecordGenerateMock implements SimpleJob {

    @DubboReference
    private CarService carService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private DeviceService deviceService;
    @DubboReference
    private MongoCarAccessRecordService carAccessRecordService;
    @DubboReference
    private PreWarningRecordService preWarningRecordService;


    @Override
    public void execute(ShardingContext shardingContext) {
        generateCarRecord();
    }

    public void generateCarRecord() {
        if (!MockLimit.enableMock() || MockLimit.mockVillageCodes() == null) {
            return;
        }
        for (String villageCode : MockLimit.mockVillageCodes()) {
            VillageDto villageDto = villageService.selectByCode(villageCode);
            if (villageDto == null) {
                continue;
            }

            List<DeviceDto> result = new ArrayList<>();
            int pageNo = 0;
            Map<String, Object> queryDevicesMap = new HashMap<>();
            queryDevicesMap.put(LambdaUtil.getFieldName(DeviceDto::getVillageId), villageDto.getId());
            queryDevicesMap.put("limit", 1000);
            while (true) {
                queryDevicesMap.put("offset", pageNo++ * 1000);
                queryDevicesMap.put("deviceCategoryCode", DeviceCategoryCodeConstants.INTELLIGENT_PARKING_GATE);
                List<DeviceDto> list = deviceService.queryList(queryDevicesMap);
                if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                    break;
                }
                result.addAll(list);
                if (list.size() < 1000) {
                    break;
                }
            }

            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("villageId", villageDto.getId());
            List<GenerateCarRecordVo> carDtos = new ArrayList<>();
            List<CarDto> listVos = new ArrayList<>();
            CarDto carDtoOne = carService.selectOne(villageDto.getId(), "陕EVA516", (byte) 1);
            listVos.add(carDtoOne);
            GenerateCarRecordVo c1 = CopyUtils.copyObj(carDtoOne, GenerateCarRecordVo.class);

            try (InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("mock/02bb048f9d264667a430a70627be23eb.png")) {
                if (resourceAsStream != null) {
                    c1.setSnapImages(JacksonUtils.toJsonString(Arrays.asList(
                            StorageKit.uploadStreamToPublicBucketObtainUrl(resourceAsStream, "02bb048f9d264667a430a70627be23eb.png")
                    )));
                }

            } catch (Exception e) {
                log.error("上传图片出错");
            }

            carDtos.add(c1);

            CarDto carDtoTwo = carService.selectOne(villageDto.getId(), "豫FLL617", (byte) 1);
            listVos.add(carDtoTwo);
            GenerateCarRecordVo c2 = CopyUtils.copyObj(carDtoTwo, GenerateCarRecordVo.class);
            try (InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("mock/292c1b84c9994e3792ebfd912eecbbf5.png")) {
                if (resourceAsStream != null) {
                    c2.setSnapImages(JacksonUtils.toJsonString(Arrays.asList(
                            StorageKit.uploadStreamToPublicBucketObtainUrl(resourceAsStream, "292c1b84c9994e3792ebfd912eecbbf5.png")
                    )));
                }

            } catch (Exception e) {
                log.error("上传图片出错");
            }
            carDtos.add(c2);

            CarDto carDtoThree = carService.selectOne(villageDto.getId(), "京FX1874", (byte) 1);
            listVos.add(carDtoThree);
            GenerateCarRecordVo c3 = CopyUtils.copyObj(carDtoThree, GenerateCarRecordVo.class);
            try (InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("mock/6dce33e17ee84b2fa90f491756b6e730.png")) {
                if (resourceAsStream != null) {
                    c3.setSnapImages(JacksonUtils.toJsonString(Arrays.asList(
                            StorageKit.uploadStreamToPublicBucketObtainUrl(resourceAsStream, "6dce33e17ee84b2fa90f491756b6e730.png")
                    )));
                }

            } catch (Exception e) {
                log.error("上传图片出错");
            }
            carDtos.add(c3);

            CarDto carDtoFour = carService.selectOne(villageDto.getId(), "甘AV5139", (byte) 1);
            listVos.add(carDtoFour);
            GenerateCarRecordVo c4 = CopyUtils.copyObj(carDtoFour, GenerateCarRecordVo.class);
            try (InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("mock/e849f6b06926463ab62a17b6ae77e38f.png")) {
                if (resourceAsStream != null) {
                    c4.setSnapImages(JacksonUtils.toJsonString(Arrays.asList(
                            StorageKit.uploadStreamToPublicBucketObtainUrl(resourceAsStream, "e849f6b06926463ab62a17b6ae77e38f.png")
                    )));
                }

            } catch (Exception e) {
                log.error("上传图片出错");
            }
            carDtos.add(c4);

            CarDto carDtoFive = carService.selectOne(villageDto.getId(), "皖LMU521", (byte) 1);
            listVos.add(carDtoFive);
            GenerateCarRecordVo c5 = CopyUtils.copyObj(carDtoFive, GenerateCarRecordVo.class);
            try (InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("mock/8cf0b5facbec4705b9decac323e9ae7d.png")) {
                if (resourceAsStream != null) {
                    c5.setSnapImages(JacksonUtils.toJsonString(Arrays.asList(
                            StorageKit.uploadStreamToPublicBucketObtainUrl(resourceAsStream, "8cf0b5facbec4705b9decac323e9ae7d.png")
                    )));
                }

            } catch (Exception e) {
                log.error("上传图片出错");
            }
            carDtos.add(c5);

            // 模拟车辆出入记录
            for (int j = 0; j < carDtos.size(); j++) {
                SecureRandom secureRandom = new SecureRandom();
                int i = secureRandom.nextInt(result.size());
                GenerateCarRecordVo generateCarRecordVo = carDtos.get(j);
                MongoCarAccessRecordDto carAccessRecordDto = new MongoCarAccessRecordDto();
                carAccessRecordDto.setId(Snowflake.nextId());
                carAccessRecordDto.setTenantId(generateCarRecordVo.getTenantId());
                carAccessRecordDto.setVillageId(generateCarRecordVo.getVillageId());
                carAccessRecordDto.setDeviceId(result.get(i).getId());
                carAccessRecordDto.setDeviceCategoryId(result.get(i).getDeviceCategoryId());
                carAccessRecordDto.setDeviceTypeId(result.get(i).getDeviceTypeId());
                carAccessRecordDto.setCarId(generateCarRecordVo.getId());
                carAccessRecordDto.setDeviceName("gate001");
                carAccessRecordDto.setCarType(generateCarRecordVo.getCarType());
                carAccessRecordDto.setLicense(generateCarRecordVo.getLicense());
                carAccessRecordDto.setLicenseColor(generateCarRecordVo.getLicenseColor());
                carAccessRecordDto.setOutOrIn((byte) RandomUtil.randomInt(1, 3));
                carAccessRecordDto.setSnapImages(generateCarRecordVo.getSnapImages());
                carAccessRecordDto.setAccessTime(DateUtil.offsetMinute(new Date(), -RandomUtil.randomInt(20)));
                carAccessRecordService.save(carAccessRecordDto);
            }

            // 频繁进出记录生成
//            for (int i = 0; i < listVos.size(); i++) {
//                CarDto carDto = listVos.get(i);
//                preWarningRecordService.checkPreCarRecord(new Date(), carDto);
//            }
        }

    }


}
